package org.yzh.web.config;

import io.github.yezhihao.netmc.NettyConfig;
import io.github.yezhihao.netmc.Server;
import io.github.yezhihao.netmc.codec.Delimiter;
import io.github.yezhihao.netmc.core.HandlerMapping;
import io.github.yezhihao.netmc.session.SessionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.yzh.protocol.codec.JTMessageAdapter;
import org.yzh.web.endpoint.JTHandlerInterceptor;

/**
 * @author sanye
 */
@Order(Integer.MIN_VALUE)
@Configuration
@ConditionalOnProperty(value = "td-server.bsj.enable", havingValue = "true")
public class BsjConfig {

    private final JTMessageAdapter messageAdapter;
    private final HandlerMapping handlerMapping;
    private final JTHandlerInterceptor handlerInterceptor;
    private final SessionManager sessionManager;

    public BsjConfig(JTMessageAdapter messageAdapter, HandlerMapping handlerMapping,
            JTHandlerInterceptor handlerInterceptor, SessionManager sessionManager) {
        this.messageAdapter = messageAdapter;
        this.handlerMapping = handlerMapping;
        this.handlerInterceptor = handlerInterceptor;
        this.sessionManager = sessionManager;
    }

    @ConditionalOnProperty(value = "td-server.bsj.port.tcp")
    @Bean(initMethod = "start", destroyMethod = "stop")
    public Server bsjTcpServer(@Value("${td-server.bsj.port.tcp}") int port, @Value("${td-server.bsj.name}") String name) {
        return NettyConfig.custom()
                .setIdleStateTime(180, 0, 0)
                .setPort(port)
                // 标识位[2] + 消息头[21] + 消息体[1023 * 2(转义预留)] + 校验码[1] + 标识位[2]
                .setMaxFrameLength(2 + 21 + 1023 * 2 + 1 + 2)
                .setDelimiters(new Delimiter(new byte[] { 0x7e }, false))
                .setDecoder(messageAdapter)
                .setEncoder(messageAdapter)
                .setHandlerMapping(handlerMapping)
                .setHandlerInterceptor(handlerInterceptor)
                .setSessionManager(sessionManager)
                .setName(name)
                .build();
    }
}
